package com.yorick.common.util;

import java.util.Base64;

import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.*;

public class Base64UploadClass {
	// 私有化构造器
	private Base64UploadClass() {
	}

	// 事先定义一个变量存放该类的实例
	private static Base64UploadClass fileBase64 = null;

	// 对外暴露一个静态方法获取该类的实例
	public static Base64UploadClass getFileBase64() {
		if (fileBase64 == null) {
			fileBase64 = new Base64UploadClass();
		}
		return fileBase64;
	}

	/**
	 * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
	 * 
	 * @param path
	 *            生成64编码的图片的路径
	 * @return
	 */
	// 将 file 转化为 Base64
	public String fileToBase64(String path) {
		File file = new File(path);
		FileInputStream inputFile;
		try {
			inputFile = new FileInputStream(file);
			byte[] buffer = new byte[(int) file.length()];
			inputFile.read(buffer);
			inputFile.close();
			// 返回base64编码过的字节数组字符串
			return Base64.getEncoder().encodeToString(buffer);
		} catch (Exception e) {
			throw new RuntimeException("文件路径无效\n" + e.getMessage());
		}
	}

	/**
	 * 对字节数组字符串进行Base64解码并生成图片
	 * 
	 * @param base64
	 *            转换为图片的字符串
	 * @param path
	 *            将64编码生成图片的路径
	 * @return
	 */
	// 将 base64 转化为 file
	public boolean base64ToFile(String base64, String path) {
		if (base64 == null) {
			return false;
		}

		byte[] buffer;
		try {
			buffer = Base64.getDecoder().decode(base64);
			// 对异常数据进行调整
			for (int i = 0; i < buffer.length; ++i) {
				if (buffer[i] < 0) {// 调整异常数据
					buffer[i] += 256;
				}
			}
			FileOutputStream out = new FileOutputStream(path);
			out.write(buffer);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			throw new RuntimeException("base64字符串异常或地址异常\n" + e.getMessage());
		}
	}
//    boolean isSuccess = fileBase64.base64StringToImage(strs, path + returnPath,imageType);   方法二
	public  boolean base64StringToImage(String base64String, String toImagePath, String imageType) {
		try {
			byte[] bytes1 = Base64.getDecoder().decode(base64String);

			ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
			RenderedImage bi1 = ImageIO.read(bais);
			File w2 = new File(toImagePath);// 可以是jpg,png,gif格式
			if (!w2.exists()) {
				w2.createNewFile();
				System.out.println("no exist=====");
			}
			System.out.println("pass...........");
			return ImageIO.write(bi1, imageType, w2);// 不管输出什么格式图片，此处不需改动
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

}
